import os
from datetime import datetime

from flask import Flask, render_template, session, redirect, url_for, flash
from flask_moment import Moment
from flask_bootstrap import Bootstrap

from form import NameForm
from SQLiteModel import User, db

app = Flask(__name__)

bootstrap = Bootstrap(app)

moment = Moment(app)

app.config['SECRET_KEY'] = 'hard to guess string'

basedir = os.path.abspath(os.path.dirname(__file__))

app.config['SQLALCHEMY_DATABASE_URI'] = \
    'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)


@app.route('/')
def hello_world():
    return render_template('index.html', )


# @app.route('/form', methods=['GET', 'POST'])
# def form_func():
#     name = None
#     form = NameForm()
#     if form.validate_on_submit():
#         name = form.name.data
#         form.name.data = ''
#     return render_template('form.html', form=form, name=name)

# 重定向发送请求
# @app.route('/form', methods=['GET', 'POST'])
# def form_func():
#     form = NameForm()
#     if form.validate_on_submit():
#         session['name'] = form.name.data
#         return redirect(url_for('form_func'))
#     return render_template('form.html', form=form, name=session.get('name'))

# 闪现消息
# @app.route('/form', methods=['GET', 'POST'])
# def form_func():
#     form = NameForm()
#     if form.validate_on_submit():
#         old_name = session.get('name')
#         if old_name is not None and old_name != form.name.data:
#             flash('Looks like you have changed your name!')
#         session['name'] = form.name.data
#         return redirect(url_for('form_func'))
#     return render_template('form.html', form=form, name=session.get('name'))


@app.route('/form', methods=['GET', 'POST'])
def form_func():
    print(db)
    form = NameForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.name.data).first()
        if user is None:
            user = User(username=form.name.data)
            db.session.add(user)
            db.session.commit()
            session['known'] = False
        else:
            session['known'] = True
        session['name'] = form.name.data
        form.name.data = ''
        return redirect(url_for('form_func'))
    return render_template('form.html',
                           form=form, name=session.get('name'),
                           known=session.get('known', False))


@app.route('/time')
def time_func():
    return render_template('time.html', current_time=datetime.utcnow())


@app.route('/user/<name>')
def user(name):
    return render_template('user.html', name=name, )


@app.route('/500')
def func500():
    print(1 / 0)


@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500


if __name__ == '__main__':
    app.run(debug=True)
